package com.itheima.service.impl;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.anno.Flag;
import com.itheima.mapper.ClazzMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.PageResult;
import com.itheima.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;

@Service
public class ClazzServiceImpl implements ClazzService {
    @Autowired
    private ClazzMapper clazzMapper;

    @Override
    public List<Clazz> list() {
        List<Clazz> list = clazzMapper.list();
        return list;
    }

    @Override
    public void add(Clazz clazz) {
        if (clazz.getBeginDate().isAfter(clazz.getEndDate())) {
            throw new RuntimeException("开课时间不能大于结课时间！");
        }
        clazzMapper.add(clazz);
    }

    @Override
    public PageResult page(String name, LocalDate begin, LocalDate end, Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);
        Page<Clazz> Clazz = (Page<Clazz>) clazzMapper.findAll(name, begin, end);
        PageResult<Clazz> pageResult = new PageResult<>();
        pageResult.setTotal(Clazz.getTotal());
        pageResult.setRows(Clazz.getResult());

        for (Clazz clazz : Clazz.getResult()) {
            if (LocalDate.now().isAfter(clazz.getBeginDate()) && LocalDate.now().isBefore(clazz.getEndDate())) {
                clazz.setStatus("已开班");
            } else if (LocalDate.now().isBefore(clazz.getBeginDate())) {
                clazz.setStatus("未开班");
            } else {
                clazz.setStatus("已结课");
            }
        }
        return pageResult;
    }

    @Override
    public void delete(Integer id) {
        if (clazzMapper.countByClazzId(id) > 0) {
            throw new RuntimeException("对不起，当前班级下有学生，不能直接删除！");
        } else {
            clazzMapper.delete(id);
        }
    }

    @Override
    public Clazz getById(Integer id) {
        return clazzMapper.getById(id);
    }

    @Override
    public void update(Clazz clazz) {
//        规定开课时间不能大于结课时间
        if (clazz.getBeginDate().isAfter(clazz.getEndDate())) {
            throw new RuntimeException("开课时间不能大于结课时间！");
        }
        clazzMapper.update(clazz);
    }
}
